package com.wxtech.heartbeat.client;

import org.apache.log4j.Logger;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class HeartBeatClient extends Thread {

	private static Logger logger = Logger.getLogger(HeartBeatClient.class);
	// private static final Object lock = null;
	private static final int repeat = 5;
//	private static final int num_of_clients = 0;
	private static final int timeout = 10;
	// private static int index = 0;

	private String host;
	private int port;

	public HeartBeatClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public static void main(String[] args) throws Exception {
		if (args.length != 2 && args.length != 0) {
			System.out.println("Usage: HearBeatClient <host> <port>");
			System.out.println("Or: HearBeatClient      to use default, localhost 8080");
			return;
		}
		String host = "localhost";
		int port = 8080;
		if (args.length == 2) {
			host = args[0];
			port = Integer.parseInt(args[1]);
		}
		// 设置好主机和端口，打印出来看一下
		System.out.println("host=" + host + " port=" + port);

		new HeartBeatClient(host, port).execute();

		// 多线程方式运行
		// for (int i = 0; i < num_of_clients; i++) {
		// HeartBeatClient tc = new HeartBeatClient(host, port);
		// tc.start();
		// }
		// //单步运行
		// if (num_of_clients == 0)
		// new HeartBeatClient(host, port).execute();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		for (int i = 0; i < HeartBeatClient.repeat; i++) {
			talkToServer();

			try {
				if (timeout > 0)
					Thread.sleep(timeout);
			} catch (Exception e) {
				logger.error(e);
			}
		}
	}

	public void execute() {
		logger.debug("client is excuting....");
		// while (true) {
		talkToServer();

		// BufferedReader consoleReader = new BufferedReader(new
		// InputStreamReader(System.in));
		// String line;
		// try {
		// line = consoleReader.readLine();
		// //随便输点东西，就再次和服务器交互，
		// //输入exit时退出
		// if (line != null && line.length() > 0 && "exit".equals(line)) {
		// logger.info("bye bye");
		// return;
		// }
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// logger.error(e);;
		// }

		// }
	}

	private void talkToServer() {
		// netty客户端
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new HeartBeatClientHandler());
				}
			});

			ChannelFuture f = b.connect(host, port).sync();
			f.channel().closeFuture().sync();

			logger.info("To sleep " + (timeout) + "s");
		} catch (Exception e) {
			logger.error(e);
		} finally {
			workerGroup.shutdownGracefully();
		}
	}
}
